import functools
import time
import json
import frappe
import datetime
import random  # 添加 random 模块

def log_http_request(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.time()
        response_status = 200  # 默认状态码
        
        try:
            result = func(*args, **kwargs)
            cost_time_ms = int((time.time() - start_time) * 1000)
            
            # 获取响应状态码（多种方式）
            if hasattr(frappe.local, 'response') and frappe.local.response:
                response_status = frappe.local.response.get("http_status_code", 200)
            elif hasattr(result, 'get') and isinstance(result, dict):
                # 如果函数返回了状态码
                response_status = result.get('http_status_code', 200)
            
            # 记录日志
            create_http_log(
                request_method=frappe.request.method if hasattr(frappe, 'request') else 'UNKNOWN',
                request_url=frappe.request.url if hasattr(frappe, 'request') else 'UNKNOWN',
                request_params=dict(frappe.request.args) if hasattr(frappe, 'request') else {},
                request_body=get_request_body(),
                response_status=response_status,
                status="成功" if response_status == 200 else "失败",
                function_name=func.__name__,
                type="接受",
                response_body=result,
                cost_time_ms=cost_time_ms,
                remark=f"Function: {func.__name__}"
            )
            
            return result
            
        except Exception as e:
            cost_time_ms = int((time.time() - start_time) * 1000)
            
            # 获取错误状态码
            if hasattr(frappe.local, 'response') and frappe.local.response:
                response_status = frappe.local.response.get("http_status_code", 500)
            else:
                response_status = 500
            try:
                # 记录错误日志
                create_http_log(
                    request_method=frappe.request.method if hasattr(frappe, 'request') else 'UNKNOWN',
                    request_url=frappe.request.url if hasattr(frappe, 'request') else 'UNKNOWN',
                    request_params=dict(frappe.request.args) if hasattr(frappe, 'request') else {},
                    request_body=get_request_body(),
                    response_status=response_status,
                    function_name=func.__name__,
                    status="失败",
                    response_body=str(e),
                    cost_time_ms=cost_time_ms,
                    remark=f"Function Error: {func.__name__}"
                )
            except Exception as log_error:
                frappe.log_error(f"HTTP Log creation failed: {str(log_error)}")
            raise
    
    return wrapper

def get_request_body():
    """安全地获取请求体"""
    try:
        if hasattr(frappe, 'request') and frappe.request.data:
            return frappe.request.get_json() if frappe.request.data else {}
        return {}
    except:
        try:
            return str(frappe.request.data)[:1000] if frappe.request.data else {}
        except:
            return {}

def create_http_log(**kwargs):
    """创建 HTTP Log 记录的辅助函数"""
    try:
        # 生成短且唯一的请求编码
        timestamp = datetime.datetime.now().strftime('%m%d%H%M%S')  # 月日时分秒，10字符
        random_suffix = random.randint(1000, 9999)  # 4位随机数
        
        request_no = f"LOG-{timestamp}{random_suffix}"  # 总长度: 4+10+4=18字符
        
        log_doc = frappe.get_doc({
            "doctype": "HTTP Log",
            "handle": f"handle_{int(time.time()*1000)}_{random.randint(1000, 9999)}",  # 使用时间戳作为handle
            "site": frappe.local.site,
            "status": kwargs.get("status", None),
            "request_no": request_no,
            "function_name": kwargs.get('function_name',None),
            "request_url": kwargs.get('request_url', ''),
            "request_method": kwargs.get('request_method', ''),
            "request_params": json.dumps(kwargs.get('request_params', {}), ensure_ascii=False, indent=2),
            "request_body": json.dumps(kwargs.get('request_body', {}), ensure_ascii=False, indent=2) if kwargs.get('request_body') else "",
            "response_status": kwargs.get('response_status', 200),
            "response_body": safe_stringify(kwargs.get('response_body', {})),
            "cost_time_ms": kwargs.get('cost_time_ms', 0),
            "create_by": frappe.session.user if frappe.session.user else "Guest",
            "create_time": frappe.utils.now_datetime(),
            "update_by": frappe.session.user if frappe.session.user else "Guest",
            "update_time": frappe.utils.now_datetime(),
            "type": kwargs.get("type", None),
            "remark": kwargs.get('remark', '')
        })
        
        log_doc.insert(ignore_permissions=True)
        
    except Exception as e:
        # 如果日志记录本身失败，记录到系统错误日志
        frappe.log_error(f"HTTP Log creation failed: {str(e)}")

def safe_stringify(obj):
    """安全地将对象转换为字符串"""
    try:
        if isinstance(obj, (dict, list)):
            return json.dumps(obj, ensure_ascii=False, indent=2)[:5000]
        elif isinstance(obj, str):
            return obj[:5000]
        else:
            return str(obj)[:5000]
    except:
        return "Unable to serialize response"